package com.whz.generic.threads;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.event.ApplicationEventMulticaster;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;

import static org.springframework.context.support.AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME;

/**
 * 通用线程池配置类,线程隔离是推荐的最佳实践
 *
 * @author whz
 */
@Slf4j
@Configuration
public class GenericThreadPoolConfiguration {

    @Bean(destroyMethod = "shutdown")
    @ConditionalOnProperty(value = "generic.thread.pool.enable", havingValue = "on")
    public ExecutorService asyncExecutorService() {
        return DefaultCommonThreadPool.DEFAULT_THREAD_POOL.defaultAsyncExecutorService();
    }

    @Bean(destroyMethod = "shutdown")
    @ConditionalOnProperty(value = "generic.schedule.pool.enable", havingValue = "on")
    public ScheduledExecutorService asyncScheduledExecutorService() {
        return DefaultCommonThreadPool.DEFAULT_THREAD_POOL.scheduledExecutorService();
    }

    @Primary
    @Bean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
    @ConditionalOnProperty(name = "generic.event.multicaster.enable", havingValue = "on")
    public ApplicationEventMulticaster eventMultiCaster(BeanFactory beanFactory, ExecutorService executorService) {
        return new GenericSpringEventMultiCaster().tongyuEventMulticaster(beanFactory, executorService);
    }
}